package com.xxx.lib

import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import com.tencent.smtt.sdk.QbSdk
import com.xxx.lib.constant.KeyAccount
import com.xxx.lib.constant.KeySetting

/**
 * SharedPreferences相关配置
 */
object SPConfig {

    /**
     * 获取账号相关SPUtils，退出账号会清除文件
     */
    val spUtilsAccount by lazy {
        SPUtils.getInstance(KeyAccount.FILE_NAME)
    }


    /**
     * 获取设置相关SPUtils，退出账号不会清除文件
     */
    val spUtilsSetting by lazy {
        SPUtils.getInstance(KeySetting.FILE_NAME)
    }

    /**
     * 是否已经登录
     */
    var isLogin = false
        private set
        get() = spUtilsAccount.getBoolean(KeyAccount.KEY_IS_LOGIN, false)


    /**
     * token，登录成功才有
     */
    var token = ""
        private set
        get() = field.ifBlank { spUtilsAccount.getString(KeyAccount.KEY_TOKEN) }


    /**
     * 登录操作，登陆成功需要调用该方法
     * @param token 用户token
     * @return 是否登录成功
     */
    fun login(token: String?): Boolean {
        if (token.isNullOrBlank()) {
            return false
        }
        this.token = token
        spUtilsAccount.put(KeyAccount.KEY_IS_LOGIN, true)
        spUtilsAccount.put(KeyAccount.KEY_TOKEN, token)
        return true
    }

    /**
     * 退出登录操作，退出登录需要调用该方法
     */
    fun logout() {
        this.token = ""
        spUtilsAccount.clear()
        QbSdk.clearAllWebViewCache(Utils.getApp(), true)
    }

}